package com.one.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.one.bean.UserLogin;
import com.one.config.LoginConfig;
import com.one.constant.RedisPrefixConstant;
import com.one.constant.RequestReturnConstant;
import com.one.service.UserService;
import com.one.service.WechatAuthService;
import com.one.util.RedisUtils;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author ShiWen
 * @date 2022/1/14 10:06
 * @Version 1.0
 * @Description TODO 用户登陆服务接口
 */

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginServerController {
    @Autowired
    private WechatAuthService wechatAuthService;
    // redis键
    @Autowired
    private LoginConfig loginConfig;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;
    /**
     * @author ShiWen
     * @date 2022/1/14 10:29
     * @param phone 手机号
     * @param password  密码
     * @return java.lang.String
     * @description 手机号密码登录接口
     */
    @PostMapping("/doLogin")
    public RequestReturn<Map<String,Object>> phoneDoLogin(String phone, String password){
        log.info(" ---- 登录参数：手机号：{}，密码：{}",phone,password);
        // 判断用户名或密码是否正确
        UserLogin loginByPwd = userService.isLoginByPwd(phone, password);
        Map<String,Object> map = new HashMap<>();
        if (loginByPwd!=null){
            // 登录 录入token令牌
            UserVo userVo = userService.loginByPhone(phone);
            if (userVo==null){
                return RequestReturnFactory.fail(RequestReturnConstant.PHONE_PASSWORD_FAIL_CODE,
                        RequestReturnConstant.PHONE_PASSWORD_FAIL_MSG);
            }
            //生成token
            String token = UUID.randomUUID().toString().replace("-","").substring(0,24);
            // 登录令牌存入redis
            redisUtils.set(RedisPrefixConstant.LOGIN_TOKEN+token,userVo);
            map.put("token",token);
            return RequestReturnFactory.success(map);
        }
        return RequestReturnFactory.fail(RequestReturnConstant.PHONE_PASSWORD_FAIL_CODE,RequestReturnConstant.PHONE_PASSWORD_FAIL_MSG);
    }

    /**
     * @author ShiWen
     * @date 2022/1/14 15:51
     * @param
     * @return
     * @description 手机验证码登录
     */
    @PostMapping("/phoneAuth")
    public RequestReturn<Map<String,Object>> phoneAuth(String phone,String auth){
        // 判断验证码是否正确
        // 判断验证码是否存在
        Map<String,Object> map = new HashMap<>();
        if (!redisUtils.hasKey(RedisPrefixConstant.PHONE_AUTH+phone)){
            // 不存在验证码，返回验证错误 状态码 5010
            return RequestReturnFactory.fail(RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_CODE,
                    RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_MSG);
        }
        // 如果存在 判断验证码是否正确
        if (!StringUtils.pathEquals(redisUtils.get(RedisPrefixConstant.PHONE_AUTH+phone).toString(),auth)){
            // 验证码错误
            return RequestReturnFactory.fail(RequestReturnConstant.VERIFICATION_FAIL_CODE,RequestReturnConstant.VERIFICATION_FAIL_MSG);
        }
        // 判断手机号是否存在
        if (!userService.isPhone(phone)){
            // 如果不存在 ，进行注册
            boolean b = userService.regisByPhone(phone);
            if (!b){
                // 注册失败
                return RequestReturnFactory.fail(map);
            }
            // 注册成功
        }

        // 进行登录
        // 查询用户信息表
        UserVo userVo = userService.loginByPhone(phone);
        if (userVo==null){
            // 注册失败
            map.put("msg","数据库异常");
            return RequestReturnFactory.fail(map);
        }
        //生成token
        String token = UUID.randomUUID().toString().replace("-","").substring(0,24);
        // 登录令牌存入redis
        redisUtils.set(RedisPrefixConstant.LOGIN_TOKEN+token,userVo);
        map.put("token",token);
        return RequestReturnFactory.success(map);
    }

    /**
     *  生成短信验证码
     */
    @GetMapping("/sendCode")
    public RequestReturn<Map<String,Object>> sendAuthCode(String phone){
        // 生成验证码
        Map<String,Object> map = new HashMap<>();
        if (redisUtils.hasKey(RedisPrefixConstant.PHONE_AUTH+phone)){
            return RequestReturnFactory.fail();
        }
        String code = String.valueOf(Math.random()).substring(2,8);
        log.info("生成的验证码：{}",code);
        redisUtils.set(RedisPrefixConstant.PHONE_AUTH+phone,code,180);
        return RequestReturnFactory.success();
    }

    // 查看验证码
    @GetMapping("/queryCode")
    public RequestReturn<Map<String,Object>> selectAuthCode(String phone){
        Map<String,Object> map = new HashMap<>();
        if (!redisUtils.hasKey(RedisPrefixConstant.PHONE_AUTH+phone)){
            // 验证码过期
            log.info("返回信息：{}",RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_MSG);
            return RequestReturnFactory.fail(RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_CODE,
                    RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_MSG);
        }
        String codeMsg = "【蘑菇街】 本次验证码是 "+redisUtils.get(RedisPrefixConstant.PHONE_AUTH+phone) + "，请于3分钟内完成操作。";
        map.put("data",codeMsg);
        log.info("返回信息：{}",map);
        return RequestReturnFactory.success(map);
    }

    /**
     * @author ShiWen
     * @date 2022/1/17 10:43
     * @param
     * @return
     * @description 微信注册
     * 绑定手机号
     */
    @GetMapping("/bindingPhone")
    public RequestReturn<Map<String,Object>> bindingPhone(String wechatUser, String phone, String auth){
        // 判断验证码是否正确
        // 判断验证码是否存在
        Map<String,Object> map = new HashMap<>();
        if (!redisUtils.hasKey(RedisPrefixConstant.PHONE_AUTH+phone)){
            // 不存在验证码，返回验证错误 状态码 5010
            return RequestReturnFactory.fail(RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_CODE,
                    RequestReturnConstant.VERIFICATION_TIMEOUT_FAIL_MSG);
        }
        // 如果存在 判断验证码是否正确
        if (!StringUtils.pathEquals(redisUtils.get(RedisPrefixConstant.PHONE_AUTH+phone).toString(),auth)){
            // 验证码错误
            return RequestReturnFactory.fail(RequestReturnConstant.VERIFICATION_FAIL_CODE,RequestReturnConstant.VERIFICATION_FAIL_MSG);
        }
        // 判断手机号是否存在
        if (userService.isPhone(phone)){
            // 如果存在返回错误 手机号一被绑定
            return RequestReturnFactory.fail(RequestReturnConstant.PHONE_BINDING_FAIL_CODE,
                    RequestReturnConstant.PHONE_BINDING_FAIL_MSG);
        }
        JSONObject userinfo = JSON.parseObject(wechatUser);
        // 不存在进行注册
        boolean b = userService.regisByWechatBindingPhone(userinfo, phone);
        if (!b){
            // 注册失败
            return RequestReturnFactory.fail(RequestReturnConstant.SERVER_SYSTEM_CODE,
                    RequestReturnConstant.PHONE_BINDING_FAIL_MSG);
        }
        // 登录
        UserVo userVo = wechatAuthService.findWechatByOpenId(userinfo.getString("openid"));
        if (userVo==null){
            // 注册失败
            return RequestReturnFactory.fail(RequestReturnConstant.SERVER_SYSTEM_CODE,
                    RequestReturnConstant.PHONE_BINDING_FAIL_MSG);
        }
        //生成token
        String token = UUID.randomUUID().toString().replace("-","").substring(0,24);
        // 登录令牌存入redis
        redisUtils.set(RedisPrefixConstant.LOGIN_TOKEN+token,userVo);
        map.put("token",token);
        return RequestReturnFactory.success(map);
    }

}
